package org.lqq.serverRegisterAndFinder.etcd;

import org.lqq.entity.ServerAddress;

import java.util.*;

/**
 * Created by 李清泉 on 2017/11/2.
 *
 * @remark
 */
public class EtcdData {

    private Map<String,Collection<ServerAddress>> etcData;

    private static EtcdData instance;

    public static EtcdData getInstance(){
        if(instance==null){
            instance=new EtcdData();
        }
        return instance;
    }

    public void put(String serverName,Collection<ServerAddress> addresses){
        synchronized (etcData) {
            etcData.put(serverName, addresses);
        }
    }

    public void put(String serverName,ServerAddress serverAddress){
        synchronized (etcData){
            Collection<ServerAddress> serverAddresses=etcData.get(serverName);
            if(serverAddress==null){
                serverAddresses=new HashSet<>();
                etcData.put(serverName,serverAddresses);
            }
            serverAddresses.add(serverAddress);
        }
    }

    public  Collection<String> getAllServerName(){
        Set<String> keys=new HashSet<>();
        synchronized (etcData){
            for(String key:etcData.keySet()){
                keys.add(key);
            }
        }
        return keys;
    }

    public Collection<ServerAddress> get(String serverName){
        synchronized (etcData){
            return etcData.get(serverName);
        }
    }


    private EtcdData(){
        etcData=new HashMap<>();
    }
}
